package xyz.syyrjx.consumer.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.syyrjx.response.SyyrjxRpcResponse;
import xyz.syyrjx.consumer.client.exception.SyyrjxRpcConsumerException;
import xyz.syyrjx.code.SyyrjxRpcCoder;
import xyz.syyrjx.consumer.entity.SyyrjxRpcFuture;
import xyz.syyrjx.consumer.entity.SyyrjxRpcFutureHolder;


/**
 * @author 大地崩坏苍蝇兽
 * @date 2023/1/7 - 13:22
 */
public class SyyrjxRpcConsumerClientHandler extends SimpleChannelInboundHandler<String> {

    private final static Logger LOGGER = LoggerFactory.getLogger(SyyrjxRpcConsumerClientHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String str) throws Exception {
        SyyrjxRpcResponse response = SyyrjxRpcCoder.StringToObject(str);

        LOGGER.debug("客户端接收到的响应" + response);

        SyyrjxRpcFuture future = SyyrjxRpcFutureHolder.FUTURE_MAP.remove(response.getFutureId());
        if (response.isFlag()){
            LOGGER.debug("接收到成功响应消息");
            future.getPromise().setSuccess(response.getData());
        }else {
            LOGGER.debug("接收到调用异常");
            future.getPromise().setFailure((Throwable) response.getData());
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        LOGGER.error(cause.getMessage());
        cause.printStackTrace();
    }
}
